/**
 * 
 */
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Hashtable;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import Action.News;
import Bean.NewsBean;

import Login.CheckLogin;
import Utils.Constant;
import Utils.DbAccess;
import Utils.FileUtils;
import Utils.GenUtils;
import Utils.ImageUtils;
import Utils.Random;
import Utils.Thumbnail;
import Utils.ZipResponse;
import Utils.upload.FileUpload;
import Utils.upload.Section;






public class InsertUpdateNewsServlet extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 4194452284080389577L;
	
	DbAccess db = null;
	
	public void init() {
		try {
			db = new DbAccess(Constant.DB,true);
		} catch ( Exception e) {
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		process(req,res);
	}
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		process(req,res);
	}

	private void process(HttpServletRequest req, HttpServletResponse res) throws IOException {
		res.setContentType("text/html");
		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		if(!CheckLogin.check(req)){
			ZipResponse.write(
				req,
				res,
				"<html><script>window.location='blank.htm';window.parent.onAddNews('notlogin','');</script></html>",
				"UTF-8");
			return;
		}
		Connection conn = null;
		String userid = req.getSession().getAttribute("userid").toString();
		String usertype = req.getSession().getAttribute("usertype").toString();
		String folder1 = "";
		PreparedStatement stmt = null;
		try{
			conn = db.getConn();
			String rootPath = req.getRealPath("/");
			if (!rootPath.endsWith("/"))
				rootPath += "/";
			folder1 =rootPath + "WEB-INF/uploads/news/"+Random.randomString(3);
			File f = new File(folder1);
			if (!f.exists())
				f.mkdirs();
			FileUpload fileUpload = new FileUpload(f.getAbsolutePath(), 0);
			Hashtable uploads = null;
			uploads = fileUpload.getUpload(req, res);
			String action = ((Section) uploads.get("action")).getValue().trim();
			String title = ((Section)uploads.get("title")).getValue().trim();
			String summary = ((Section)uploads.get("summary")).getValue().trim();
			String content = ((Section)uploads.get("content")).getValue().trim().replace("&gt;",">").replace("&lt;","<");
			String date = ((Section)uploads.get("date")).getValue().trim();
			String source = ((Section)uploads.get("source")).getValue().trim();
			String link = ((Section)uploads.get("link")).getValue().trim();
			String keyword = ((Section)uploads.get("keyword")).getValue().trim();
			String catidlist = ((Section)uploads.get("catidlist")).getValue().trim();
			String linkpic = ((Section)uploads.get("linkpic")).getValue().trim();
			String oldHomePic = ((Section)uploads.get("oldhomepic")).getValue().trim();
			
			String newsId = "";
			if(action.equals("insert")){
				newsId = Random.randomNumber(15);	
			}else{
				newsId =  ((Section)uploads.get("newsid")).getValue().trim();
			}
			String remainedfile = ((Section)uploads.get("remainedfile")).getValue().trim();
			
			
			String folder = GenUtils.genPathByAccountId(newsId);
			String img = ImageUtils.uploadImage(uploads, folder);
			String imgdownload = "";
			if(!linkpic.equals(""))
				imgdownload=ImageUtils.downloadPic(linkpic, folder);
			String thumbnail = "";
			int hadImg = 0;
			String arr[]=new News().getImg(content, newsId, conn);
			if(arr!=null)
				content=arr[0];
			
			if(!img.equals("")){
				if(!imgdownload.equals(""))
					img = img+","+imgdownload;
				if(!remainedfile.equals(""))
					img = remainedfile+","+img;
				if(arr!=null && !arr[1].equals(""))
					img = img+","+arr[1];
			}else{
				img = imgdownload;
				if(!imgdownload.equals(""))
					img = remainedfile+","+imgdownload;
				else
					img = remainedfile;
				if(!img.equals("")){
					if(arr!=null && !arr[1].equals(""))
						img = img+","+arr[1];
				}else{
					if(arr!=null && !arr[1].equals(""))
						img = arr[1];
				}
			}
			if(!img.equals("")){
				hadImg = 1;
				thumbnail = img.split(",")[0];
//				new Thumbnail().ThumbnailImage(folder+Constant.FILE_SEPARATOR+thumbnail,
//						folder +Constant.FILE_SEPARATOR+thumbnail.replace(".", "thumb."),
//						Constant.IMAGE_SMALL_THUMBHEIGHT,
//						Constant.IMAGE_SMALL_THUMBWIDTH);
//				thumbnail = thumbnail.replace(".", "thumb.");			
			}
			
			
			
			
			
			
			NewsBean newsBean = new NewsBean();
			newsBean.setNewsId(newsId);
			newsBean.setTitle(title);
			newsBean.setSummary(summary);
			newsBean.setSource(source);
			newsBean.setLink(link);
			newsBean.setKeyword(keyword);
			newsBean.setPicture(img);
			newsBean.setHadImg(hadImg);
			newsBean.setThumbnail(thumbnail);
			newsBean.setContent(content);
			newsBean.setDatePublished(date);
			newsBean.setTempCat(0);
			newsBean.setStatus(0);
			newsBean.setTotalNews(1);
			newsBean.setPoster(userid);
			
			String homeimg=ImageUtils.uploadHomePic(oldHomePic, uploads, folder);
			
			if(action.equals("insert")){
				if(new News().insertNews(newsBean, conn)){
					if(new News().insertCat(catidlist, newsId, conn)){
						
						if(!homeimg.equals("")){
							String sql = "UPDATE news SET HomePic=? WHERE NewsId=?";
							stmt = conn.prepareStatement(sql);
							stmt.setString(1, homeimg);
							stmt.setString(2, newsId);
							stmt.executeUpdate();
						}else{
							ZipResponse.write(req,res,"<html><script>window.location='blank.htm';window.parent.onAddNews('true','"+newsId+"');</script></html>",
							"UTF-8");
							return;
						}
						ZipResponse.write(req,res,"<html><script>window.location='blank.htm';window.parent.onAddNews('true','"+newsId+"');</script></html>",
								"UTF-8");
						return;
					}
				}
			}else{
				if(new News().updateNews(newsBean, conn,userid,usertype)){
					if(new News().insertCat(catidlist, newsId, conn)){
						if(!homeimg.equals("")){
							String sql = "UPDATE news SET HomePic=? WHERE NewsId=?";
							stmt = conn.prepareStatement(sql);
							stmt.setString(1, homeimg);
							stmt.setString(2, newsId);
							stmt.executeUpdate();
						}else{
							ZipResponse.write(req,res,"<html><script>window.location='blank.htm';window.parent.onAddNews('true','"+newsId+"');</script></html>",
							"UTF-8");
							return;
						}
						ZipResponse.write(req,res,"<html><script>window.location='blank.htm';window.parent.onAddNews('true','"+newsId+"');</script></html>",
								"UTF-8");
						return;
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			
		}finally{
			if(stmt!=null){try{stmt.close();}catch (Exception e) {}}
			if(conn!=null){try{conn.close();}catch (Exception e) {}}
			FileUtils.deleteDir(new File(folder1));
		}
		ZipResponse.write(req,res,"<html><script>window.location='blank.htm';window.parent.onAddNews('false','');</script></html>",
				"UTF-8");
	}
	
}
